<template>
  <el-select
    class="tree-select-box"
    v-model="selectedLabel"
    :clearable="true"
    :filterable="true"
    :placeholder="$t('请选择')"
    :disabled="disabled"
    @clear="handleClear"
    @focus="handleFocus"
  >
    <el-option
      :value="selectedValue"
      :label="selectedLabel"
      style="height: auto"
    >
      <el-tree
        ref="tree"
        :data="data"
        :props="props"
        :node-key="nodeKey"
        :default-expand-all="defaultExpandAll"
        :highlight-current="true"
        :expand-on-click-node="false"
        @node-click="handleNodeClick"
      ></el-tree>
    </el-option>
  </el-select>
</template>
<script>
export default {
  name: 'ElTreeSelect',
  props: {
    // 树形数据
    data: {
      type: Array,
      required: true,
    },
    // 配置选项
    props: {
      type: Object,
      default: () => ({
        children: 'children',
        label: 'label',
      }),
    },
    // 节点key
    nodeKey: {
      type: String,
      default: 'id',
    },
    // 默认是否展开所有节点
    defaultExpandAll: {
      type: Boolean,
      default: false,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    // 选中的值
    value: {
      type: [String, Number],
      default: '',
    },
  },
  data() {
    return {
      selectedValue: '',
      selectedLabel: '',
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(newVal) {
        if (newVal) {
          this.setSelectedNode(newVal)
        } else {
          this.selectedValue = ''
          this.selectedLabel = ''
        }
      },
    },
  },
  methods: {
    // 设置选中的节点
    setSelectedNode(value) {
      this.$nextTick(() => {
        if (this.$refs.tree) {
          this.$refs.tree.setCurrentKey(value)
          const node = this.$refs.tree.getNode(value)
          if (node) {
            this.selectedValue = node.data[this.nodeKey]
            this.selectedLabel = node.data[this.props.label]
          }
        }
      })
    },
    // 节点点击事件
    handleNodeClick(data, node) {
      this.selectedValue = data[this.nodeKey]
      this.selectedLabel = data[this.props.label]
      this.$emit('input', this.selectedValue)
      this.$emit('change', this.selectedValue, this.selectedLabel, data)
      // 点击后关闭下拉框
      this.$refs.select.blur()
    },
    // 清空选择
    handleClear() {
      this.selectedValue = ''
      this.selectedLabel = ''
      this.$emit('input', '')
      this.$emit('change', '', '')
    },
    // 获取焦点时展开树
    handleFocus() {
      this.$nextTick(() => {
        if (this.$refs.tree && this.selectedValue) {
          this.$refs.tree.setCurrentKey(this.selectedValue)
        }
      })
    },
  },
}
</script>
<style scoped>
.tree-select-box {
  width: 100%;
}
.el-scrollbar .el-scrollbar__view .el-select-dropdown__item {
  padding: 0;
}
.el-select-dropdown__item.selected {
  font-weight: normal;
}
</style>
